#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
打包脚本 - 将代码提取器打包成exe文件
使用PyInstaller进行打包
"""

import os
import subprocess
import sys
import shutil
import tkinter as tk
from tkinter import messagebox

def check_pyinstaller():
    """检查是否安装了PyInstaller"""
    try:
        import PyInstaller
        return True
    except ImportError:
        return False

def install_pyinstaller():
    """安装PyInstaller"""
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "pyinstaller"])
        return True
    except subprocess.CalledProcessError:
        return False

def install_dependencies():
    """安装所需的依赖"""
    try:
        # 安装python-docx（可选依赖）
        subprocess.check_call([sys.executable, "-m", "pip", "install", "python-docx"])
        return True
    except subprocess.CalledProcessError:
        return False

def build_exe():
    """打包成exe文件"""
    try:
        # 构建命令
        cmd = [
            "pyinstaller",
            "--name=代码提取器",
            "--windowed",  # 使用GUI模式，不显示控制台
            "--onefile",   # 打包成单个exe文件
            "--icon=icon.ico" if os.path.exists("icon.ico") else "",  # 如果有图标文件则使用
            "--add-data=README.md;.",  # 添加README文件
            "code_extractor.py"  # 主程序文件
        ]
        
        # 移除空选项
        cmd = [item for item in cmd if item]
        
        # 执行打包命令
        subprocess.check_call(cmd)
        
        # 检查是否成功生成exe文件
        exe_path = os.path.join("dist", "代码提取器.exe")
        if os.path.exists(exe_path):
            # 将exe文件复制到当前目录
            shutil.copy(exe_path, ".")
            return True
        return False
    except subprocess.CalledProcessError:
        return False

def main():
    """主函数"""
    # 创建简单的GUI
    root = tk.Tk()
    root.title("代码提取器 - 打包工具")
    root.geometry("500x300")
    
    frame = tk.Frame(root, padx=20, pady=20)
    frame.pack(fill=tk.BOTH, expand=True)
    
    tk.Label(frame, text="代码提取器 - 打包工具", font=("Arial", 14, "bold")).pack(pady=10)
    
    # 检查PyInstaller
    has_pyinstaller = check_pyinstaller()
    pyinstaller_status = "已安装" if has_pyinstaller else "未安装"
    tk.Label(frame, text=f"PyInstaller: {pyinstaller_status}", anchor="w").pack(fill=tk.X, pady=5)
    
    # 状态标签
    status_label = tk.Label(frame, text="", anchor="w")
    status_label.pack(fill=tk.X, pady=5)
    
    # 安装PyInstaller按钮
    def on_install_pyinstaller():
        status_label.config(text="正在安装PyInstaller...")
        root.update()
        
        if install_pyinstaller():
            status_label.config(text="PyInstaller安装成功！")
            install_button.config(state=tk.DISABLED)
            build_button.config(state=tk.NORMAL)
        else:
            status_label.config(text="安装失败，请尝试手动安装: pip install pyinstaller")
    
    install_button = tk.Button(frame, text="安装PyInstaller", command=on_install_pyinstaller)
    install_button.pack(pady=5)
    
    if has_pyinstaller:
        install_button.config(state=tk.DISABLED)
    
    # 安装依赖按钮
    def on_install_dependencies():
        status_label.config(text="正在安装依赖...")
        root.update()
        
        if install_dependencies():
            status_label.config(text="依赖安装成功！")
        else:
            status_label.config(text="部分依赖安装失败，但可以继续打包")
    
    tk.Button(frame, text="安装依赖(python-docx)", command=on_install_dependencies).pack(pady=5)
    
    # 打包按钮
    def on_build_exe():
        status_label.config(text="正在打包，请稍候...")
        root.update()
        
        if build_exe():
            status_label.config(text="打包成功！exe文件已生成在当前目录。")
            messagebox.showinfo("成功", "打包成功！exe文件已生成在当前目录。")
        else:
            status_label.config(text="打包失败，请查看控制台输出。")
            messagebox.showerror("错误", "打包失败，请查看控制台输出。")
    
    build_button = tk.Button(frame, text="打包成exe", command=on_build_exe)
    build_button.pack(pady=10)
    
    if not has_pyinstaller:
        build_button.config(state=tk.DISABLED)
    
    # 退出按钮
    tk.Button(frame, text="退出", command=root.destroy).pack(pady=5)
    
    # 提示信息
    tk.Label(frame, text="注意：打包过程可能需要几分钟，请耐心等待", fg="blue").pack(pady=10)
    
    root.mainloop()

if __name__ == "__main__":
    main() 